// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.datainterface.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.query.QueryGenerator;
import com.fowo.api.datainterface.entity.DatainterfaceMapping;
import com.fowo.api.datainterface.mapper.DatainterfaceMappingMapper;
import com.fowo.api.datainterface.model.DatainterfaceMappingSearchParamPo;
import com.fowo.api.datainterface.model.DatainterfaceMappingVo;
import com.fowo.api.datainterface.model.DatainterfaceTaskVo;
import com.fowo.api.datainterface.service.DatainterfaceMappingService;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 映射 服务实现基类
 */
@Slf4j
@DS("ds21")
@Service
public class DatainterfaceMappingServiceImpl
        extends ServiceImpl<DatainterfaceMappingMapper, DatainterfaceMapping>
        implements DatainterfaceMappingService {

    public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
    // 导出时单次查询最大记录数
    protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
    // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
    protected static final long EXPORT_MAX_SIZE = 1048575;

    @Resource
    protected FileService fileService;

    @Resource
    protected SysImportTemplateService importTemplateService;

    @Resource
    protected Validator validator;


    /**
     * 创建映射
     *
     * @param model 映射
     * @return 新数据的主键
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(DatainterfaceMappingVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        DatainterfaceMapping entity = new DatainterfaceMapping();
        BeanUtils.copyProperties(model, entity);
        entity.setCreateTime(new Date());
        entity.setLastUpdateTime(new Date());
        if (currentUser != null) {
            entity.setCreateUser(currentUser.getUserId());
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (this.save(entity)) {
            return entity.getId();
        }
        throw new Exception("映射保存失败");
    }

    /**
     * 批量更新 数据接口事务 下属数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAllByDatainterfaceTaskTaskMapping(
            DatainterfaceTaskVo parentVo,
            List<DatainterfaceMapping> list
    ) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        for (DatainterfaceMapping itemVo : list) {
            if (
                    itemVo.getId() != null &&
                            !itemVo.getDelFlag()
            ) {
                // 删除处理
                this.delete(itemVo.getId());
                continue;
            }
            DatainterfaceMapping item = new DatainterfaceMapping();
            BeanUtils.copyProperties(itemVo, item);
            item.setCreateTime(new Date());
            item.setLastUpdateTime(new Date());
            if (currentUser != null) {
                item.setCreateUser(currentUser.getUserId());
                item.setLastUpdateUser(currentUser.getUserId());
            }
            item.setTaskCode(parentVo.getTaskCode());
            if (item.getId() == null) {
                this.save(item);
            } else {
                this.updateById(item);
            }
        }
    }

    /**
     * 更新映射
     *
     * @param model 映射
     * @return 更新是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(DatainterfaceMappingVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        DatainterfaceMapping entity = this.getById(model.getId());
        if (entity == null) {
            throw new Exception("映射不存在");
        }
        BeanUtils.copyProperties(
                model,
                entity,
                "id",
                "lastUpdateUser",
                "lastUpdateTime",
                "createUser",
                "createTime"
        );
        entity.setLastUpdateTime(new Date());
        if (currentUser != null) {
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (this.updateById(entity)) {
            return true;
        }
        return false;
    }

    /**
     * 更新映射（带空值）
     *
     * @param model 映射
     * @return 更新是否成功
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateForEdit(DatainterfaceMappingVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        DatainterfaceMapping entity = this.getById(model.getId());
        if (entity == null) {
            throw new Exception("映射不存在");
        }
        model.setLastUpdateTime(new Date());
        if (currentUser != null) {
            model.setLastUpdateUser(currentUser.getUserId());
        }
        boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
                .set(DatainterfaceMapping::getTaskCode, model.getTaskCode())
                .set(DatainterfaceMapping::getSyncFlagField, model.getSyncFlagField())
                .set(DatainterfaceMapping::getColSysariables, model.getColSysariables())
                .set(DatainterfaceMapping::getColType, model.getColType())
                .set(DatainterfaceMapping::getPrimaryKeyTo, model.getPrimaryKeyTo())
                .set(DatainterfaceMapping::getFieldNameTo, model.getFieldNameTo())
                .set(DatainterfaceMapping::getFieldTo, model.getFieldTo())
                .set(DatainterfaceMapping::getEnCodeTo, model.getEnCodeTo())
                .set(DatainterfaceMapping::getAllowNullFrom, model.getAllowNullFrom())
                .set(DatainterfaceMapping::getDataLengthFrom, model.getDataLengthFrom())
                .set(DatainterfaceMapping::getDataTypeFrom, model.getDataTypeFrom())
                .set(DatainterfaceMapping::getFieldNameFrom, model.getFieldNameFrom())
                .set(DatainterfaceMapping::getFieldFrom, model.getFieldFrom())
                .set(DatainterfaceMapping::getEnCodeFrom, model.getEnCodeFrom())
                .set(DatainterfaceMapping::getLastUpdateUser, model.getLastUpdateUser())
                .set(DatainterfaceMapping::getLastUpdateTime, model.getLastUpdateTime())
                .eq(DatainterfaceMapping::getId, model.getId())
                .update();
        if (isOk) {
        }
        return isOk;
    }

    /**
     * 删除映射
     *
     * @param id 映射的主键
     * @return 删除是否成功
     */
    @Override
    public boolean delete(Long id) throws Exception {
        return this.removeById(id);
    }

    /**
     * 批量删除映射
     *
     * @param ids 映射的主键列表
     * @return 删除是否成功
     */
    @Override
    public boolean batchDelete(List<Long> ids) throws Exception {
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 通过事务编码查询映射主键(重复时返回最新的主键)
     */
    @Override
    public Long getIdByTaskCode(String taskCode) {
        return this.getObj(Wrappers.<DatainterfaceMapping>lambdaQuery().select(DatainterfaceMapping::getId).eq(DatainterfaceMapping::getTaskCode, taskCode), res -> Convert.toLong(res));
    }

    /**
     * 通过事务编码查询映射多主键(重复时返回最新的主键)
     */
    @Override
    public List<Long> getIdsByTaskCode(List<String> list) {
        return this.listObjs(Wrappers.<DatainterfaceMapping>lambdaQuery().select(DatainterfaceMapping::getId).in(DatainterfaceMapping::getTaskCode, list), res -> Convert.toLong(res));
    }

    /**
     * 通过映射主键查询事务编码
     */
    @Override
    public String getTaskCodeById(Long id) {
        return this.getObj(Wrappers.<DatainterfaceMapping>lambdaQuery().select(DatainterfaceMapping::getTaskCode).eq(DatainterfaceMapping::getId, id), res -> Convert.toStr(res));
    }

    /**
     * 通过映射主键查询事务编码列表
     */
    @Override
    public List<String> getTaskCodeByIds(List<Long> ids) {
        return this.listObjs(Wrappers.<DatainterfaceMapping>lambdaQuery().select(DatainterfaceMapping::getTaskCode).in(DatainterfaceMapping::getId, ids), res -> Convert.toStr(res));
    }

    /**
     * 获取详情
     *
     * @param id 映射的主键
     */
    @Override
    public DatainterfaceMappingVo getVoById(Long id) throws Exception {
        DatainterfaceMapping vo = this.getById(id);
        if (vo == null) {
            return null;
        }
        return BeanUtil.copyProperties(vo, DatainterfaceMappingVo.class);
    }

    /**
     * 分页查询映射
     *
     * @param search 查询条件
     * @return 映射分页查询结果
     */
    @Override
    public Page<DatainterfaceMapping> pageSearch(
            DatainterfaceMappingSearchParamPo search
    ) {
        DatainterfaceMapping DatainterfaceMapping = BeanUtil.copyProperties(search, DatainterfaceMapping.class);
        QueryWrapper<DatainterfaceMapping> queryWrapper = QueryGenerator.initQueryWrapper(DatainterfaceMapping, search);
        Page<DatainterfaceMapping> pageList = this.page(search.toPage(), queryWrapper);
        return pageList;
    }

    /**
     * 列表查询映射
     *
     * @param search 查询条件
     * @return 映射列表查询结果
     */
    @Override
    public List<DatainterfaceMapping> search(
            DatainterfaceMappingSearchParamPo search
    ) {
        DatainterfaceMapping DatainterfaceMapping = BeanUtil.copyProperties(search, DatainterfaceMapping.class);
        QueryWrapper<DatainterfaceMapping> queryWrapper = QueryGenerator.initQueryWrapper(DatainterfaceMapping, search);
        return this.list(queryWrapper);
    }

    /**
     * 查询映射最后更新时间
     *
     * @param search 查询条件
     * @return 映射最后更新时间
     */
    @Override
    public Date searchLastUpdateTime(DatainterfaceMappingSearchParamPo search) {
        DatainterfaceMapping DatainterfaceMapping = BeanUtil.copyProperties(search, DatainterfaceMapping.class);
        QueryWrapper<DatainterfaceMapping> queryWrapper = QueryGenerator.initQueryWrapper(DatainterfaceMapping, search, null, null);
        queryWrapper.select("max(last_update_time) last_update_time");
        return this.getObj(queryWrapper, res -> Convert.toDate(res));
    }
}
